﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using DBClient;
using UserManagment;

namespace Protocols {

	enum Errors {
		ERR_UsernameIsTaken,
		ERR_UsernameLoggedIn,
		ERR_UsernameNotExists,
		ERR_UsernameRegistered,
		ERR_BadPassword
	}

	class Protocols {
	}

	abstract class Protocol {

	}

	class SignInProtocol : Protocol {

		DBConnection dbConnection;
		public SignInProtocol(DBConnection dbConnection) {
			this.dbConnection = dbConnection;
		}
		public Errors signIn(string user, string pass) {
			//string query = string.Format("SELECT `Username`, `Password` From `PlayersDB` WHERE `Username`='{0}'", user);
			//string selectPass = string.Format("SELECT `Password` From `PlayersDB` WHERE `Password`='{0}'", pass);
			/*
			string resUser = dbConnection.selectScalar(selectUser);
			string resPass = dbConnection.selectScalar(selectPass);
			*/
			//string[] res = dbConnection.selectLine(query);
			//Console.WriteLine("resUser: {0}\tresPass: {1}", res[0], res[1]);
			//if (Usermanagment.DBConnection)

			string	queryPass = string.Format("SELECT `Password` From `PlayersDB` WHERE `Username`='{0}'", user);
			string	resPass = dbConnection.selectScalar(queryPass);
			// to add disconnect sql
			if (resPass.Length == 0) {
				return Errors.ERR_UsernameNotExists;
			}
			else if (!resPass.Equals(pass)) {
				return Errors.ERR_BadPassword;
			}
			else {
				return Errors.ERR_UsernameLoggedIn;
			}
		}
	}

	class SignUpProtocol : Protocol {

		DBConnection dbConnection;
		public SignUpProtocol(DBConnection dbConnection) {
			this.dbConnection = dbConnection;
		}
		public Errors signUp(string user, string pass) {
			string query = String.Format("SELECT `Username` FROM `PlayersDB` WHERE `Username`='{0}'", user);
			string res = Convert.ToString(dbConnection.selectScalar(query));

			if (!String.IsNullOrEmpty(res)) {
				return Errors.ERR_UsernameIsTaken;
			}

			int time = FinalProject_Poker.Tools.MachineTime.GetCurrentSeconds();
			string queryRegisterUser = String.Format("INSERT INTO `PlayersDB` (`Username`, `Password`, `DateReg`) VALUES ('{0}', '{1}', '{2}')", user, pass, time);
			//Console.WriteLine(queryRegisterUser);
			this.dbConnection.Update(queryRegisterUser);
			// add disconnect sql
			return Errors.ERR_UsernameRegistered;
		}
	}

	class UsernameIsTakenException : Exception {
		public UsernameIsTakenException() { }
	}
}
